const fs = require('fs');
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const appDir = fs.realpathSync(process.cwd());
let wasmFile = './node_modules/@jd/jd-bsplayer/src/components/hPlayer/libffmpeg.wasm';
if (!fs.existsSync(wasmFile)) {
  wasmFile = '../../node_modules/@jd/jd-bsplayer/src/components/hPlayer/libffmpeg.wasm';
}
module.exports = {
  custom: {
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        src: path.resolve(__dirname, './src'),
      },
    },
    module: {
      rules: [
        {
          test: [/jd-bsplayer\/src.*\.js$/i, /videoControl\/index\.js$/i],
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react'],
            plugins: ['@babel/plugin-proposal-class-properties'],
          },
        },
        {
          test: /\.worker\.(c|m)?js$/i,
          loader: 'worker-loader',
        },
      ],
    },
    plugins: [
      new CopyWebpackPlugin([
        {
          from: wasmFile,
          to: './static/js/libffmpeg.wasm',
        },
      ]),
    ],
  },
  override: (config) => {
    config.module.rules[2].oneOf[2].options.babelrc = true;
    config.module.rules[2].oneOf[2].options.configFile = true;
    if (process.env.NODE_ENV === 'development' && !process.env.WIDGET_PATH) {
      require('@jkyu/monet-studio-reqeust')();
    }
    const loaders = config.module.rules;
    loaders.splice(loaders.length - 1, 0, {
      test: /\.svg$/,
      loader: 'svg-sprite-loader',
      // 只处理指定的svg文件
      include: path.resolve(appDir, 'node_modules/@jd/jd-bsplayer/src/icons'),
      options: {
        symbolId: 'svg-icon-[name]',
      },
    });
    return config;
  },
};
